package com.hzncc.flowable_diboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.binding.QueryBuilder;
import com.diboot.core.service.impl.BaseServiceImpl;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.S;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.util.IamSecurityUtils;
import com.hzncc.flowable_diboot.dto.BusinessDTO;
import com.hzncc.flowable_diboot.entity.*;
import com.hzncc.flowable_diboot.mapper.BusinessMapper;
import com.hzncc.flowable_diboot.mapper.BusinessTeamMapper;
import com.hzncc.flowable_diboot.mapper.BusinessUserMapper;
import com.hzncc.flowable_diboot.service.*;
import com.hzncc.flowable_diboot.util.ConstantUtil;
import com.hzncc.flowable_diboot.vo.BusinessListVO;
import com.hzncc.flowable_diboot.vo.OppoFlowOrderDetailVO;
import com.hzncc.flowable_diboot.vo.OppoFlowOrderItemDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * 商机 相关Service实现类
 *
 * @author MyName
 * @version 1.0
 * @date 2024-06-06
 * Copyright © MyCorp
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessServiceImpl extends BaseServiceImpl<BusinessMapper, Business> implements BusinessService {
    private final OppoFlowOrderService oppoFlowOrderService;
    private final CommonService commonService;
    private final BusinessUserMapper businessUserMapper;
    private final OppoFlowOrderItemService oppoFlowOrderItemService;
    private final CustomConnectorService customConnectorService;
    private final BusinessContactService businessContactService;
    private final BusinessTeamMapper businessTeamMapper;

    @Override
    protected void afterCreate(Business entity) {
        createOrUpdateN2NRelations(BusinessUser::getBusiness, entity.getId(), BusinessUser::getUser, entity.getStarUids());
    }

    @Override
    protected void afterUpdate(Business entity) {
        createOrUpdateN2NRelations(BusinessUser::getBusiness, entity.getId(), BusinessUser::getUser, entity.getStarUids());
    }

    @Override
    public OppoFlowOrderDetailVO selectFlowOrder(String id) {
        Business bus = getEntity(id);
        String orderId = bus.getOrderId();
        return oppoFlowOrderService.selectOrder(orderId);
    }

    @Override
    public void create(Business business) {
        business.setOfficeId(commonService.getOffice(business.getUid()));
        String flowTemplateId = business.getFlowTemplateId();
        //if (StringUtils.isBlank(flowTemplateId)) {
        //    // 获取默认模板
        //    OppoFlowTemplate tmp = oppoFlowTemplateService.getSingleEntity(QueryBuilder.toQueryWrapper(new OppoFlowTemplateDTO().setIsDefault(true)));
        //    if (tmp == null) {
        //        throw new RuntimeException("未获取到默认流程模板，请手动选择模板");
        //    }
        //    flowTemplateId = tmp.getId();
        //}
        String orderId = oppoFlowOrderService.createOrder(flowTemplateId);
        business.setOrderId(orderId);
        business.setFlowTemplateId(flowTemplateId);
        createEntity(business);
        // 同步客户联系人
        QueryWrapper<CustomConnector> queryWrapper = new QueryWrapper<CustomConnector>()
                .eq("customer_id", business.getCustomerId());
        List<CustomConnector> contacts = customConnectorService.getEntityList(queryWrapper);
        List<BusinessContact> contactList = new ArrayList<>();
        for (CustomConnector contact : contacts) {
            BusinessContact businessContact = new BusinessContact();
            businessContact.setBusinessId(business.getId());
            businessContact.setUid(contact.getUserId());
            businessContact.setContactInformation(contact.getConnectWay());
            businessContact.setSex(contact.getGender());
            businessContact.setName(contact.getConnector());
            businessContact.setTitle(contact.getTitle());
            contactList.add(businessContact);
        }
        businessContactService.createEntities(contactList);
    }

    @Override
    public void flowCommit(OppoFlowOrderDetailVO detailVO, String itemId) {
        oppoFlowOrderService.commit(detailVO, itemId);
    }

    @Override
    public List<BusinessListVO> selectBusiness(BusinessDTO queryDto, Pagination pagination, String type) {
        if (pagination != null && V.isEmpty(pagination.getOrderBy())) {
            pagination.setOrderBy(Pagination.ORDER_BY_ID_DESC);
        }
        // 我的商机
        if (Objects.equals("resp", type)) {
            queryDto.setUid(IamSecurityUtils.getCurrentUserId());
        }
        // 赢单的商机
        if (Objects.equals("win", type)) {
            queryDto.setWinType("win");
        }
        QueryWrapper<Business> queryWrapper = QueryBuilder.toQueryWrapper(queryDto, pagination);
        if (commonService.isCrossTenant(IamSecurityUtils.getCurrentTenantId())){
            return getViewObjectList(queryWrapper, pagination, BusinessListVO.class);
        }
        // 下属负责的商机
        if (Objects.equals("sub", type)) {
            List<String> subEmp = commonService.findSubEmp(IamSecurityUtils.getCurrentUser());
            if (subEmp.isEmpty()) {
                return new ArrayList<>();
            }
            List<String> teamBusiness = getTeamBusiness(subEmp, queryDto);
            queryWrapper.in("uid", subEmp);
            if (teamBusiness.size() > 0) {
                queryWrapper.or().in("id", teamBusiness);
            }
        }
        // 全部商机
        if (Objects.equals("self", type)) {
            List<String> subEmp = commonService.findSubEmp(IamSecurityUtils.getCurrentUser());
            subEmp.add(IamSecurityUtils.getCurrentUserId());
            queryWrapper.in("uid", subEmp);
            List<String> teamBusiness = getTeamBusiness(subEmp, queryDto);
            if (teamBusiness.size() > 0) {
                queryWrapper.or().in("id", teamBusiness);
            }
        }
        // 我关注的商机
        if (Objects.equals("star", type)) {
            List<String> ids = businessUserMapper.selectStar(IamSecurityUtils.getCurrentUserId());
            if (ids == null || ids.isEmpty()) {
                return new ArrayList<>();
            }
            queryWrapper.in("id", ids);
        }
        return getViewObjectList(queryWrapper, pagination, BusinessListVO.class);
    }

    /**
     * 获取人员团队负责的商机
     *
     * @param uids 成员id
     * @return
     * @author 陈广煜
     * @date 2024/6/24
     */
    private List<String> getTeamBusiness(List<String> uids, BusinessDTO dto) {
        QueryWrapper<BusinessTeam> qw = new QueryWrapper<>();
        qw.in("member_id", uids);
        List<BusinessTeam> businessTeams = businessTeamMapper.selectList(qw);
        List<String> bus = BeanUtils.collectToList(businessTeams, BusinessTeam::getBusinessId);
        QueryWrapper queryWrapper = QueryBuilder.toQueryWrapper(dto);
        if (bus.isEmpty()){
            return new ArrayList<>();
        }
        queryWrapper.in("id", bus);
        List<Business> entityList = getEntityList(queryWrapper);
        return BeanUtils.collectToList(entityList, Business::getId);
    }

    /**
     * 流程提交
     *
     * @param item 流程阶段
     */
    @Override
    public JsonResult<?> flowCommit(OppoFlowOrderItemDetailVO item, String res) {
        OppoFlowOrder order = oppoFlowOrderService.getEntity(item.getOrderId());
        order.setStatus(ConstantUtil.FLOW_TYPE_GOING);
        // 获取商机
        QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", item.getOrderId());
        Business business = getSingleEntity(queryWrapper);
        if (S.equals(business.getStatus(), ConstantUtil.FLOW_TYPE_OVER)) {
            return JsonResult.FAIL_INVALID_PARAM("流程已结束，不能再提交！");
        }
        business.setStatus(ConstantUtil.FLOW_TYPE_GOING);
        // 最后节点 结束
        if (S.isNotBlank(res)) {
            business.setStage(convert(res));
            business.setStatus(ConstantUtil.FLOW_TYPE_OVER);
            business.setWinType(res);
            order.setResult(res);
            order.setStatus(ConstantUtil.FLOW_TYPE_OVER);
            order.setIsOver(true);
        }
        if (item.getIsCurrent()) {
            // 获取下一节点
            String nextId = item.getNext();
            if (S.isNotBlank(nextId)) {
                OppoFlowOrderItem nextItem = oppoFlowOrderItemService.getEntity(nextId);
                business.setStage(nextItem.getName());
                // 流程未提前结束 推进流程
                nextItem.setIsCurrent(S.isBlank(res));
                item.setIsCurrent(S.isNotBlank(res));
                oppoFlowOrderItemService.updateEntity(nextItem);
            }
            oppoFlowOrderItemService.updateEntity(item);
        } else {
            QueryWrapper<OppoFlowOrderItem> qw = new QueryWrapper<>();
            qw.eq("order_id", item.getOrderId());
            List<OppoFlowOrderItem> items = oppoFlowOrderItemService.getEntityList(qw);
            items.sort(Comparator.comparing(OppoFlowOrderItem::getSort));
            int current = -1; // 当前正在进行的流程index
            int itemIndex = 0; // 提交的流程 index
            for (int i = 0; i < items.size(); i++) {
                if (items.get(i).getIsCurrent()) {
                    current = i;
                }
                if (Objects.equals(items.get(i).getId(), item.getId())) {
                    itemIndex = i;
                }
            }
            if (itemIndex > current && S.isBlank(res) && current != -1) {
                return JsonResult.FAIL_EXCEPTION("前置流程未结束,不能提交!");
            }
        }
        oppoFlowOrderService.updateEntity(order);
        //oppoFlowOrderDetailService.updateEntities(item.getDetails());
        this.updateEntity(business);
        return JsonResult.OK();
    }

    @Override
    public JsonResult<?> flowStage(OppoFlowOrderItemDetailVO item) {
        OppoFlowOrder order = oppoFlowOrderService.getEntity(item.getOrderId());
        order.setStatus(ConstantUtil.FLOW_TYPE_GOING);
        // 获取商机
        QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", item.getOrderId());
        Business business = getSingleEntity(queryWrapper);
        if (S.equals(business.getStatus(), ConstantUtil.FLOW_TYPE_OVER)) {
            return JsonResult.FAIL_INVALID_PARAM("流程已结束，不能再提交！");
        }
        String res = item.getRes();
        // 最后节点 结束
        if (S.isNotBlank(res)) {
            business.setStage(convert(res));
            business.setStatus(ConstantUtil.FLOW_TYPE_OVER);
            business.setWinType(res);
            order.setResult(res);
            order.setStatus(ConstantUtil.FLOW_TYPE_OVER);
            order.setIsOver(true);
        }
        oppoFlowOrderItemService.updateEntity(item);
        //oppoFlowOrderDetailService.updateEntities(item.getDetails());
        this.updateEntity(business);
        return JsonResult.OK();
    }

    /**
     * 赢单状态转换
     *
     * @param res
     * @return
     * @author 陈广煜
     * @date 2024/6/19
     */
    private String convert(String res) {
        switch (res) {
            case "win":
                return "赢单";
            case "lose":
                return "输单";
            case "invalid":
                return "无效";
            default:
                return res;
        }
    }
}